/**
 * @author fanxuean
 * @link fanshine124@gmail.com
 * @description 任务发布页面包装器，采用惰性实例化单体模式，入口是init函数，返回包装器对象
 * @return Object {}
 */
MIDB.Model.MissionAnnounce = (function(){
    var uniqueInstance;
    function constructor() {
        var p = {};
        // var dataCache = null;
        var curPage = 1;
        var pages = 1;
        var pageSize = 30;
        var limitPerEmployeeType = 10; // 每个雇员类别最多雇佣人数
        /**
         * [getEmployeeTypes 查询雇员列表]
         * @param  {[type]} sortName  [description]
         * @param  {[type]} sortOrder [description]
         * @return {[type]}           [description]
         */
        var getEmployeeTypes = function(sortName, sortOrder) {
            var param = {
                page: curPage,
                pageSize: pageSize,
                sortName: sortName,
                sortOrder: sortOrder
            };
            $.ajax({
              url: MIDB.ajaxUrl.employee_type,
              type: 'POST',
              dataType: 'json',
              data: {atype: 'r', param: param, timestamp: new Date().getTime()},
              complete: function(xhr, textStatus) {
                //called when complete
              },
              success: function(data, textStatus, xhr) {
                if(!!data && !!data.Rows) {
                    createNewMission(data.Rows);
                    compilePagination(data.curPage, data.pages);
                }
              },
              error: function(xhr, textStatus, errorThrown) {
                //called when there is an error
              }
            });
        };
        /**
         * [compilePagination 渲染分页栏]
         * @param  {[type]} cur [description]
         * @param  {[type]} all [description]
         * @return {[type]}     [description]
         */
        var compilePagination = function(cur, all) {
            var pageContainer = $(p.contentContainer).find('.pagination'),
                tmpl = p.pageTmpl.html(),
                doTtmpl = doT.template(tmpl);
            curPage = cur;
            pages = all;
            pageContainer.html(doTtmpl({curPage: cur, pages: pages}));
            bindPageEvent(pageContainer);
        };
        /**
         * [bindPageEvent 绑定分页栏事件]
         * @param  {[type]} pageContainer [description]
         * @return {[type]}               [description]
         */
        var bindPageEvent = function(pageContainer) {
            $(pageContainer)
            .find('.prePage').click(function(event) {
                if(curPage > 1) curPage--;
                getEmployeeTypes();
                event.stopPropagation();
            }).end()
            .find('.nextPage').click(function(event) {
                if(curPage < pages) curPage++;
                getEmployeeTypes();
                event.stopPropagation();
            }).end()
            .find('select[name=jumpPage]').change(function(event) {
                curPage = $(this).val();
                getEmployeeTypes();
                event.stopPropagation();
            });
        };
        /**
         * [getRecommendList 获取推荐雇员]
         * @param  {[type]} param [description]
         * @return {[type]}       [description]
         */
        var getRecommendList = function(d) {
            var missionEmployeeList = [];
            if(d.m_employee_num) {
                $(d.m_employee_num.split(',')).each(function(event) {
                    var d = this.split(':'),
                        eTypeCode = d[0],
                        num = d[1];
                    missionEmployeeList.push({employeeTypeCode: eTypeCode, employeeNum: num});
                });
            }
            $.ajax({
                url: MIDB.ajaxUrl.push_employee,
                type: 'POST',
                dataType: 'json',
                data: {param: missionEmployeeList},
                complete: function(xhr, textStatus) {
                //called when complete
                },
                success: function(data, textStatus, xhr) {
                    if(!!data && data.length > 0) {
                        d.data = data;
                        completeRecommendHtml(d);
                    } else {
                        alert('获取推荐人员失败');
                    }
                },
                error: function(xhr, textStatus, errorThrown) {
                    alert('获取推荐人员失败');
                }
            });

        };
        /**
         * [completeRecommendHtml 渲染推荐雇员页面]
         * @param  {[type]} data [description]
         * @return {[type]}      [description]
         */
        var completeRecommendHtml = function(data) {
            var tmpl = $('#new_mission_step2_tmpl').html(),
                doTtmpl = doT.template(tmpl);
            p.tmplContainer.html(doTtmpl(data));
            bindRecommendPageEvent();
        };
        /**
         * [bindRecommendPageEvent 绑定推荐雇员页面事件]
         * @return {[type]} [description]
         */
        var bindRecommendPageEvent = function() {
            p.tmplContainer.find('input[name=nextMissionStep2]').click(function(event) {
                var missionCode = $(this).attr('mCode');
                getSelectedEmployees(p.tmplContainer.find('.employee_select_list2'), missionCode);
            }).end()
            .find('input[name=deleteMission]').click(function(event) {
                var missionCode = $(this).attr('mCode');
                $.ligerDialog.confirm('是否确定删除该任务', function(yes) {
                    if(yes) deleteMission(missionCode);
                });
            }).end()
            .find('input[type=checkbox]').click(function(event) {
                var cType = $(this).attr('name'),
                    limit = $(this).parents('ul.employee_list_select').attr('en'),
                    selected = 0;
                $(p.tmplContainer).find('input[name=' + cType + ']').each(function(event) {
                    if($(this).attr('checked')) selected++;
                });
                if(selected > limit) {
                    alert('不可超过所需人数');
                    return false;
                }
            });
        };
        /**
         * [getSelectedEmployees 获取选择的雇员]
         * @param  {[type]} employeeSelectObj [description]
         * @return {[type]}                   [description]
         */
        var getSelectedEmployees = function(employeeSelectObj, mCode) {
            var selectedEmployees = [];
            $(employeeSelectObj).find('input[type=checkbox]').each(function(event) {
                if($(this).attr('checked')) {
                    var uid = $(this).attr('uid');
                    selectedEmployees.push(uid);
                }
            });
            if(selectedEmployees.length > 0) updateNewMission(selectedEmployees.join(','), mCode);
        };
        var updateNewMission = function(selectedEmployees, mCode) {
            var param = {
                m_code: mCode,
                m_employees: selectedEmployees
            };
            $.ajax({
              url: MIDB.ajaxUrl.mission_list,
              type: 'POST',
              dataType: 'text',
              data: {atype: 'u', param: param},
              complete: function(xhr, textStatus) {
                //called when complete
              },
              success: function(data, textStatus, xhr) {
                if(data == 1) {
                    alert('新建任务成功,等待审核');
                    $('#main_content').find('.user_menu_box').find("li:eq(1)").trigger('click');
                }
              },
              error: function(xhr, textStatus, errorThrown) {
                alert('新建任务失败');
              }
            });


        };
        /**
         * [createNewMission 加载新建任务第一步页面]
         * @param  {[type]} data [description]
         * @return {[type]}      [description]
         */
        var createNewMission = function(data) {
            var tmpl = p.tmpl.html(),
                doTtmpl = doT.template(tmpl);
            p.tmplContainer.html(doTtmpl(data));
            completeHtml();
        };
        var insertNewMission = function(data) {
            $.ajax({
              url: MIDB.ajaxUrl.mission_list,
              type: 'POST',
              dataType: 'text',
              data: {atype: 'c', param: data},
              complete: function(xhr, textStatus) {
                //called when complete
              },
              success: function(data, textStatus, xhr) {
                if(data != 1) {
                    alert('新建任务失败');
                    return false;
                }
                $('#main_content').find('.user_menu_box').find("li:eq(1)").trigger('click');
              },
              error: function(xhr, textStatus, errorThrown) {
                alert('新建任务失败');
              }
            });

        };
        /**
         * [completeHtml 初始化新建任务第一步页面组件]
         * @return {[type]} [description]
         */
        var completeHtml = function() {
            p.tmplContainer.find('input[name=mission_end_time]').ligerDateEditor({
                // showTime : true,
                format : 'yyyy-MM-dd',
                label : '',
                labelWidth : 100,
                labelAlign : 'left'
            });
            bindEvent();
        };
        /**
         * [bindEvent 绑定新建任务第一步页面事件]
         * @return {[type]} [description]
         */
        var bindEvent = function() {
            p.tmplContainer.find('input[name=mission_name]').one('keydown', function(event) {
                $(this).val('');
            }).end()
            .find('.decrease').on('click', function(event) {
                var inputObj = $(this).siblings('input[name=employee_num_input]'),
                    curNum = +(inputObj.val());
                if(curNum > 0) inputObj.val(curNum - 1);
            }).end()
            .find('.increase').on('click', function(event) {
                var inputObj = $(this).siblings('input[name=employee_num_input]'),
                    curNum = +(inputObj.val());
                if(curNum < limitPerEmployeeType) inputObj.val(curNum + 1);
            }).end()
            .find('input[name=nextMissionStep]').click(function(event) {
                var missionName = p.tmplContainer.find('input[name=mission_name]').val(),
                    missionEndTime = p.tmplContainer.find('input[name=mission_end_time]').val(),
                    missionDesc = p.tmplContainer.find('textarea[name=mission_desc]').val(),
                    // missionEmployeeList = [],
                    mEmployeeNum = [];
                // todo validate form
                p.tmplContainer.find('.employee_select_list tr').each(function(event) {
                    var num = $(this).find('.employee_num_input').val(),
                        eTypeCode = $(this).find('.employee_type > span').attr('et'),
                        eType = $(this).find('.employee_type > span').text();
                    if(parseInt(num, 10) > 0) {
                        // missionEmployeeList.push({employeeType: eType, employeeTypeCode: eTypeCode, employeeNum: num});
                        mEmployeeNum.push(eTypeCode + ':' + num);
                    }
                });
                var dataCache = {
                    user_code: MIDB.cache.user.user_code,
                    m_name: missionName,
                    m_end_date: missionEndTime,
                    m_desc: missionDesc,
                    m_employee_num: mEmployeeNum.join(',')
                };
                insertNewMission(dataCache);
            });
        };
        return {
            init: function(options) {
                p = $.extend({}, p||{}, options || {});
                getEmployeeTypes();
                return this;
            },
            showModel: function(param) {
                if(param.actype === "modify") {
                    createNewMission(param.data);
                } else if(param.actype === "selectEmployee") {
                    getRecommendList(param.data);
                }
            }
        };
    }
    return {
        getInstance : function() {
            if (!uniqueInstance) {
                uniqueInstance = constructor();
            }
            return uniqueInstance;
        }
    };
})();